﻿using ServiceMonitor.Core;
using ServiceMonitor.Model;
using ServiceMonitor.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ServiceMonitor.Services.Impl
{
    /// <summary>
    /// TCP/IP端口监控服务实现类
    /// </summary>
    public class TcpIPPortMonitorServiceImpl : AbstractStartMonitoringService
    {

        private readonly Action<String> _logger;
        private readonly MonitorConfig _config;
        private Action<string> logger;
        private Timer _monitoringTimer;
        private static Object lock_obj = new Object();
        public TcpIPPortMonitorServiceImpl(
            EventHandler<ServiceStatusChangedEventArgs> eventHandler,
            MonitorConfig config,
            Action<string> logger) : base(eventHandler)
        {
            this._config = config;
            this.logger = logger;

        }

        public override void Start(Object obj)
        {
            _monitoringTimer = new Timer(CheckServiceStatus, null, Timeout.Infinite, Timeout.Infinite);
            _monitoringTimer.Change(0, _config.CheckInterval * 1000);
        }

        public override void CheckServiceStatus(object state)
        {
            lock (lock_obj)
            {
                if (!MonitoringService.GetIsMonitoring())
                {
                    return;
                }
                try
                {
                    try
                    {
                        using (var client = new TcpClient())
                        {
                            // 设置1秒超时
                            var result = client.BeginConnect(_config.Host, _config.Port, null, null);
                            bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
                            if (success && client.Connected)
                            {
                                client.EndConnect(result);
                                UpdateStatus(_config.Id, $"端口 {_config.Port} 连接成功");
                            }
                            else
                            {
                                client.Close();
                                throw new TimeoutException("连接超时");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        UpdateStatus(_config.Id, $"端口检测失败: {ex.Message}");
                    }
                }
                catch (Exception ex)
                {
                    logger?.Invoke($"端口检测失败: {ex.Message}");
                }
            }
        }

    }
}
